var app = getApp();
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var user = require('../../../services/user.js');

// miniprogram/components/action/action.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginRes: {},
    sessionKey:'',
    openId:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    wx.login({
      success: function (loginRes) {
        that.setData({
          loginRes: loginRes
        });
      },
      fail: function (err) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '取消授权',
          success: function (res) {
            console.log(res)
            // 拒绝授权确定后到逻辑处理
          }
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {



  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 获取用户昵称头像
  getUserProfile() {

    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于展示个人中心头像，昵称', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);
        // 授权拿到昵称头像后处理的逻辑
        this.requestAuthFunction(res);
      },
      fail: (err) => {
        console.log(err);
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '取消授权',
          success: function (res) {
            console.log(res)
            // 拒绝授权确定后到逻辑处理
          }
        })
      }
    });

  },
  requestAuthFunction(infoRes) {
    wx.request({
      url: api.AuthLoginByWeixin,
      method: "post",
      header: {
        'appId': 'wx27c83f987452ccec'
      },
      data: {
        code: this.data.loginRes.code,
        rawData: infoRes.rawData, //用户非敏感信息
        signature: infoRes.signature, //签名
        encryptedData: infoRes.encryptedData, //用户敏感信息
        iv: infoRes.iv //解密算法的向量
      },
      success: function (res) {
        console.log('login success');
        console.log("res:", res)
        wx.setStorageSync('token', res.data.data.access_token);
        wx.setStorageSync('userInfo', res.data.data);
        console.log("token=" + res.data.data.access_token);
        wx.navigateBack();
      },
      fail: function (error) {
        //调用服务端登录接口失败
        console.log(error);
        wx.navigateBack();
      }
    });
  },

  /** 用户信息 */
  doLogin: function (callback = () => {}) {
    let that = this;
    wx.login({
      success: function (loginRes) {
        if (loginRes) {
          that.requestSessionFunction(loginRes);
        } else {

        }
      }
    });
  },
  requestSessionFunction(infoRes) {
    let that = this;
    wx.request({
      url: api.AuthLoginBySessionKey,
      method: "post",
      header: {
        'appId': 'wx27c83f987452ccec'
      },
      data: {
        code: this.data.loginRes.code,
        rawData: infoRes.rawData, //用户非敏感信息
        signature: infoRes.signature, //签名
        encryptedData: infoRes.encryptedData, //用户敏感信息
        iv: infoRes.iv //解密算法的向量
      },
      success: function (res) {
        console.log('login success');
        console.log("res:", res)
        wx.setStorageSync('token', res.data.data.access_token);
        wx.setStorageSync('userInfo', res.data.data);
        console.log("token=" + res.data.data.access_token);
        that.setData({
          sessionKey: res.data.data.sessionKey,
          openId: res.data.data.openId
        });
        //wx.navigateBack();
      },
      fail: function (error) {
        //调用服务端登录接口失败
        console.log(error);
        wx.navigateBack();
      }
    });
  },

  getPhoneNumber: function (e) {
    var that = this;
    console.log(e.detail.errMsg == "getPhoneNumber:ok");
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.request({
        url: api.AuthLoginByPhone,
        method: "post",
        header: {
          'appId': 'wx27c83f987452ccec'
        },
        data: {
          code:  that.data.loginRes.code,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          sessionKey: that.data.sessionKey,
          openId: that.data.openId,
          uid: "",
        },
        method: "post",
        success: function (res) {
          console.log(res);
        }
      })
    }
  },
})